package leetcode;

import java.util.*;

public class LevelOrder {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        TreeNode right = new TreeNode(20);
        root.right = right;
        right.left = new TreeNode(15);
        right.right = new TreeNode(7);
        LevelOrder levelOrder = new LevelOrder();
        System.out.println(Arrays.toString(levelOrder.levelOrder(root)));
    }

    /**
     * 剑指 Offer 32 - I. 从上到下打印二叉树
     * 思路：
     * 1.创建一个空队列
     * 2.先将根节点入队，此后每次出队，都要将其左、右节点入队
     * 3.出队的元素存入结果中
     *
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        ArrayList<Integer> list = new ArrayList<>();
        while (!queue.isEmpty()) {
            if (root.left != null) {
                queue.add(root.left);
            }
            if (root.right != null) {
                queue.add(root.right);
            }
            list.add(queue.remove().val);
            root = queue.peek();
        }

        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}
